package com.zx.mobile.controller;

import com.alibaba.fastjson.JSONObject;
import com.zx.jd.util.PropertyUtils;
import com.zx.map.dao.model.MerchantTokenAuto;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.MerchantTokenService;
import com.zx.platform.utils.StrUtils;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 对接接口-内购商城 2.0
 * Created by LMC on 2017/8/8.
 */
@Controller
@RequestMapping("/mobile/neiGouOpen")
public class NeiGouOpenController {

    private static Logger log = Logger.getLogger(NeiGouController.class);

    @Autowired
    private MerchantTokenService merchantTokenService;
    @Autowired
    private MerchantInfoService merchantInfoService;

    PropertyUtils propertyUtils = new PropertyUtils("neiGouOpen.properties");

    /**
     *  client_credentials模式获取令牌
     */
    @RequestMapping("/getAccessTokenSpecific")
    public void getAccessTokenSpecific(String merchantId, HttpServletRequest request, HttpServletResponse response) {
        try {
            MerchantTokenAuto tokenAuto;
            tokenAuto = merchantTokenService.getOneById(merchantId);

            String neiGouId ;
            if (StrUtils.isEmpty(tokenAuto)) {
                Date date = new Date();
                neiGouId = merchantId;

                MerchantTokenAuto merchantTokenAuto = new MerchantTokenAuto();
                merchantTokenAuto.setMerchantId(merchantId);
                merchantTokenAuto.setNeigouId(neiGouId);
                merchantTokenAuto.setCreateDate(date);
                merchantTokenAuto.setUpdateDate(date);
                merchantTokenService.add(merchantTokenAuto);
            } else {
                neiGouId = tokenAuto.getNeigouId();
            }

            //client_credentials获取AccessToken获取
            String httpUrl = propertyUtils.getStringByKey("token_url");
            OkHttpClient client = new OkHttpClient();
            FormBody body = new FormBody.Builder()
                    .add("client_id", propertyUtils.getStringByKey("client_id"))
                    .add("client_secret", propertyUtils.getStringByKey("client_secret"))
                    .add("grant_type", propertyUtils.getStringByKey("grant_type"))
                    .build();
            Request req = new Request.Builder()
                    .url(httpUrl)
                    .post(body)
                    .build();
            Response resp = client.newCall(req).execute();
            if (resp.isSuccessful()) {
                String string = resp.body().string();
                JSONObject jsonObject = (JSONObject) JSONObject.parse(string);
                boolean result = Boolean.parseBoolean(jsonObject.get("Result").toString());
                if (result) {
                    Object data = jsonObject.get("Data");
                    JSONObject obj = (JSONObject) JSONObject.parse(data.toString());
                    Object accessToken = obj.get("access_token");
                    MerchantTokenAuto auto = new MerchantTokenAuto();
                    auto.setMerchantId(merchantId);
                    auto.setAccessToken(accessToken.toString());
                    auto.setUpdateDate(new Date());
                    merchantTokenService.update(auto);

                    //用户登录网关
                    String gatewayUrl = propertyUtils.getStringByKey("login_gateway_url");
                    String furl = propertyUtils.getStringByKey("furl");
                    String surl = propertyUtils.getStringByKey("surl");
                    String client_id = propertyUtils.getStringByKey("client_id");

                    furl += "&merchantId="+merchantId;
                    furl= URLEncoder.encode(furl,"UTF-8");

                    String url = gatewayUrl+"?client_id="+client_id+"&user="+neiGouId+"&furl="+furl+"&surl="+surl;
                    response.sendRedirect(url);

                } else {
//                    System.out.println("====获取令牌登录内购====异常"+jsonObject);
                    log.error("====获取令牌登录内购====异常"+jsonObject);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("====获取令牌====异常", e);
        }


    }

    /**
     *  创建用户登录使用的login_token
     * @param merchantId
     */
    @RequestMapping("/createAutoLoginURL")
    public void createAutoLoginURL(String merchantId,HttpServletResponse response) {
        try {
            String httpUrl=propertyUtils.getStringByKey("create_login_token_url");
            MerchantTokenAuto tokenAuto = merchantTokenService.getOneById(merchantId);

            OkHttpClient client = new OkHttpClient();
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("external_user_id",tokenAuto.getNeigouId());

            FormBody body = new FormBody.Builder()
                    .add("data", jsonObj.toString())
                    .build();

            Request req = new Request.Builder()
                    .url(httpUrl)
                    .post(body)
                    .addHeader("AUTHORIZATION","Bearer "+tokenAuto.getAccessToken())
                    .build();
            Response resp = client.newCall(req).execute();

            if (resp.isSuccessful()) {
                String string = resp.body().string();
                JSONObject jsonObject = (JSONObject) JSONObject.parse(string);
                boolean result = Boolean.parseBoolean(jsonObject.get("Result").toString());
                if (result) {
                    Object data = jsonObject.get("Data");
                    JSONObject obj = (JSONObject) JSONObject.parse(data.toString());
                    Object loginToken = obj.get("login_token");

                    //使用login_token登录用户
                    String loginGatewayUrl=propertyUtils.getStringByKey("login_gateway_url");

                    String surl = propertyUtils.getStringByKey("surl");
                    String furl = propertyUtils.getStringByKey("furl")+"&merchantId="+merchantId;

                    String url = loginGatewayUrl+"?login_token="+loginToken+"&force=true&furl="+furl+"&surl="+surl;
                    response.sendRedirect(url);

                } else {
                    log.error("======创建login_token登录内购商城=====返回异常"+jsonObject);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("======创建login_token登录内购商城=====请求异常", e);
        }
    }


    /**
     * 创建用户
     * @param merchantId
     * @throws IOException
     */
    @RequestMapping("/createUser")
    public void createUser(String merchantId,HttpServletResponse response) throws IOException {
        try {
            String httpUrl = propertyUtils.getStringByKey("create_user_url");
            MerchantTokenAuto tokenAuto = merchantTokenService.getOneById(merchantId);

            //初始用户名：6位随机的字符串
            String merchantName = RandomStringUtils.random(6,true,true);;

            OkHttpClient client = new OkHttpClient();
            JSONObject obj = new JSONObject();
            obj.put("external_user_id",tokenAuto.getNeigouId());
            obj.put("nickname",merchantName);
            obj.put("name",merchantName);

            FormBody body = new FormBody.Builder()
                    .add("data",obj.toString())
                    .build();

            Request req = new Request.Builder()
                    .url(httpUrl)
                    .addHeader("AUTHORIZATION","Bearer "+tokenAuto.getAccessToken())
                    .post(body)
                    .build();
            Response resp = client.newCall(req).execute();

            if (resp.isSuccessful()) {
                String string = resp.body().string();
                JSONObject jsonObject = (JSONObject) JSONObject.parse(string);
                boolean result = Boolean.parseBoolean(jsonObject.get("Result").toString());
                if (result) {
                    String open_create_login_token_interface_url = propertyUtils.getStringByKey("create_login_token_interface_url");
                    response.sendRedirect(open_create_login_token_interface_url+"?merchantId="+merchantId);
                } else {
//                    System.out.println("======创建用户=====返回异常" + jsonObject);
                    log.error("======创建用户=====返回异常" + jsonObject);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("======创建用户=====请求异常", e);
        }
    }


    /**
     *  处理错误情况
     * @param err
     * @param merchantId
     */
    @RequestMapping("/dealError")
    public void dealError(String err, String merchantId,HttpServletResponse response) {
        try {
            /**
             *    NG_ERRCODE错误值：
             *    ERR_NOT_LOGIN 用户未登录
             *    ERR_DIFF_USER 已经登录了不同的用户
             *    ERR_COMPANY_OR_USER_NOT_ACCESSABLE 用户或公司不存在
             */
            String url = null;

            if (err.equals("ERR_NOT_LOGIN")) {
                url = propertyUtils.getStringByKey("create_login_token_interface_url")+"?merchantId="+merchantId;
            } else if (err.equals("ERR_DIFF_USER")) {
                url = propertyUtils.getStringByKey("create_login_token_interface_url")+"?merchantId="+merchantId;
            } else if (err.equals("ERR_COMPANY_OR_USER_NOT_ACCESSABLE")) {
                url = propertyUtils.getStringByKey("create_user_interface_url")+"?merchantId="+merchantId;
            }

//            System.out.println("err = " + err);
            response.sendRedirect(url);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内购登录异常", e);
        }
    }
}
